#include "mylineedit.h"
#include "QLineEdit"
#include <QMessageBox>

MyLineEdit::MyLineEdit(QWidget *parent) : QLineEdit(parent)
{
}

void MyLineEdit::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::KeypadModifier)
    {
        switch (event->key())
        {
        case Qt::Key_0:
            numpadKeyPressed(0);
            break;
        case Qt::Key_1:
            numpadKeyPressed(1);
            break;
        case Qt::Key_2:
            numpadKeyPressed(2);
            break;
        case Qt::Key_3:
            numpadKeyPressed(3);
            break;
        case Qt::Key_4:
            numpadKeyPressed(4);
            break;
        case Qt::Key_5:
            numpadKeyPressed(5);
            break;
        case Qt::Key_6:
            numpadKeyPressed(6);
            break;
        case Qt::Key_7:
            numpadKeyPressed(7);
            break;
        case Qt::Key_8:
            numpadKeyPressed(8);
            break;
        case Qt::Key_9:
            numpadKeyPressed(9);
            break;
        case Qt::Key_Enter:
            QLineEdit::keyPressEvent(event);
            break;
        }
    }
    else if (event->modifiers() == Qt::Key_Control)
    {
        switch (event->key())
        {
        case Qt::Key_Minus:
            break;
        case Qt::Key_Plus:
            break;
        }
    }

    else if (event->modifiers() == Qt::ControlModifier)
    {
        switch (event->key())
        {
        case Qt::Key_B:
            ctrlKeyComboPressed("b");
            break;
        case Qt::Key_S:
            ctrlKeyComboPressed("s");
            break;
        }
    }

    else
    {
        switch (event->key())
        {
        case Qt::Key_Return:
            upCounter = 0;
            if (history.count() > 0)
            {
                if (history.last() != this->text())
                    history.append(this->text());
            }
            else
                history.append(this->text());
            break;
        case Qt::Key_Up:
            updateCounter(true);
            break;
        case Qt::Key_Down:
            updateCounter(false);
            break;
        }
        QLineEdit::keyPressEvent(event);
    }
}

void MyLineEdit::updateCounter(bool increment)
{
    if (history.count() > 0)
    {
        if (increment)
        {
            if (upCounter < history.count())
                upCounter++;
            else
                upCounter = history.count() - 1;
        }

        else
        {
            if (upCounter > 0)
                upCounter--;
            else
                upCounter = 0;
        }

        if (upCounter != 0 && upCounter < history.count())
        {
            this->setText(history.at(history.count() - upCounter));
            this->selectAll();
        }
    }
}
